import decompress from 'decompress'
import {isEmpty} from '../utils'
import path from 'path'
import os from 'os'
import * as uuid from 'uuid'
import fs from 'fs'

/**
 * 解压一个压缩文件到指定目录
 * @param filePath 压缩文件路径
 * @param destDir 解压目标文件路径,Optional
 * @param opts decompress.DecompressOptions,Optional
 * @returns {Promise<void>} 解压的目标文件路径
 */
export async function extract(
    filePath: string,
    destDir?: string,
    opts?: decompress.DecompressOptions,
): Promise<string> {
    return new Extractor(decompress).extract(filePath, destDir, opts)
}

export class Extractor {
    private readonly decompressFunc: typeof decompress;

    constructor(decompressFunc: typeof decompress) {
        this.decompressFunc = decompressFunc;
    }

    async extract(
        filePath: string,
        destDir?: string,
        opts?: decompress.DecompressOptions,
    ): Promise<string> {
        if (isEmpty(destDir) || destDir == null) {
            destDir = path.join(os.tmpdir(), uuid.v4())
        }
        fs.mkdirSync(destDir, {recursive: true})
        await this.decompressFunc(filePath, destDir, opts)
        return destDir
    }
}